package cn.lysj.framework.order.util.wx;

import cn.lysj.framework.common.utils.http.HttpUtil;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.order.dto.PayParam;
import cn.lysj.framework.order.dto.RefundParam;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 微信统一下单工具
 *
 * @author Administrator
 */
@Slf4j
public class UnifiedOrderUtil {

    private static final String UNIFIED_ORDER_URL = "https://mp.changepay.cn/wxpay/unifiedorder"; // post请求,微信统一下单接口


    private final static String spbill_create_ip = "127.0.0.1";

    private final static String trade_type = "JSAPI";

    private final static String fee_type = "CNY";

    private final static String notify_url = "http://diet.lingyundata.com:8080/app/v2/user/wx_order_callback";
//    private final static String notify_url = "http://test.diet.lingyundata.com:8080/app/v2/user/wx_order_callback";


    public static Map<String, String> createMap(PayParam model) {
        Map<String, String> params = new TreeMap<String, String>();
        params.put("attach", model.getAttach());// 授权码
        params.put("mch_id", model.getMchId());// 商户号
        params.put("orgNo", model.getOrgNo());// 机构号
        params.put("device_info", model.getDeviceInfo());// 终端号
        params.put("openid", model.getOpenid());// 微信用户openid
        params.put("nonce_str", model.getNonceStr()); // 随机字符
        params.put("total_fee", String.valueOf(model.getTotalFee()));// 总金额
        params.put("out_trade_no", model.getOutTradeNo());// 订单号
        params.put("notify_url", notify_url); // 异步地址
        params.put("spbill_create_ip", spbill_create_ip);// 终端IP
        params.put("trade_type", trade_type);// 交易类型
        params.put("fee_type", fee_type);// 费用类型
        return params;
    }


    public static String sign(Map<String, String> paramMap, String appKey) {
        log.info("传入的私钥:" + appKey);
        StringBuilder sb = new StringBuilder();
        for (String key : paramMap.keySet()) {
            log.info(key + "{}" + paramMap.get(key));
            sb.append(key).append("=").append(paramMap.get(key)).append("&");
        }
        sb.append("key=").append(appKey);
        return ParamUtil.md5(sb.toString()).toUpperCase();
    }

    public static String createXml(Map<String, String> params) {

        String xml = "<xml>"
                + "<attach>" + stringChange(params.get("attach")) + "</attach>"
                + "<device_info>" + stringChange(params.get("device_info")) + "</device_info>"
                + "<mch_id>" + params.get("mch_id") + "</mch_id>"
                + "<openid>" + stringChange(params.get("openid")) + "</openid>"
                + "<orgNo>" + params.get("orgNo") + "</orgNo>"
                + "<nonce_str>" + stringChange(params.get("nonce_str")) + "</nonce_str>"
                + "<notify_url>" + stringChange(params.get("notify_url")) + "</notify_url>"
                + "<out_trade_no>" + stringChange(params.get("out_trade_no")) + "</out_trade_no>"
                + "<spbill_create_ip>" + stringChange(params.get("spbill_create_ip")) + "</spbill_create_ip>"
                + "<total_fee>" + params.get("total_fee") + "</total_fee>"
                + "<trade_type>" + stringChange(params.get("trade_type")) + "</trade_type>"
                + "<fee_type>" + stringChange(params.get("fee_type")) + "</fee_type>"
                + "<sign>" + stringChange(params.get("sign")) + "</sign>"
                + "</xml>";
        log.info("生成的XML:+" + xml);
        return xml;
    }

    public static String sendPrePay(String xml) {
        String result = HttpUtil.sendJsonPost(UNIFIED_ORDER_URL, xml);
        log.info("发起统一下单接口时返回的数据:\n" + result);
        return result;
    }

    public static String stringChange(String str) {
        return String.format("<![CDATA[%s]]>", str);
    }

    public static Map<String, String> creatRefundParams(RefundParam model) {
        Map<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("orgNo", model.getOrgNo());//商户号
        packageParams.put("device_info", model.getDeviceInfo());//商户号
        packageParams.put("mch_id", model.getMchId());//商户号
        packageParams.put("nonce_str", ParamUtil.uuid());//随机字符串
        packageParams.put("transaction_id", model.getTransactionId());//订单号
        packageParams.put("out_refund_no", ParamUtil.uuid());//退款单号
        packageParams.put("total_fee", String.valueOf(model.getTotalFee()));//订单总金额
        packageParams.put("refund_fee", String.valueOf(model.getReturnFee()));//退款总金额
        packageParams.put("refund_fee_type", fee_type);//退款总金额
        return packageParams;
    }

    public static String signMd5_2(Map<String, String> packageParams, String appKey) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + appKey);
        String sign = ParamUtil.md5(sb.toString()).toUpperCase();
        return sign;
    }

}
